//
//  manageMyVC.swift
//  DingDongZP
//
//  Created by 三秒文化 on 16/4/9.
//  Copyright © 2016年 iyhjiang.com. All rights reserved.
//

import UIKit

class manageMyResumeVC: UIViewController {
    
    var tableView:UITableView?
    var addJobTitleBtn:UIButton?
    var selectTitleArr = [AnyObject]()
    var myUserInfo = [String:AnyObject]()
    
    //选中的按钮
    var preSelBtn:UIButton?
    
    var myExpectJobArr = [AnyObject]()
    var myExpectModelArr = [LDUserInfoExpectedJobModel]()
    
    
    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        sendRequest()
        setDefaultContent()
    }
    
    func setupData() {
        
        myExpectJobArr.removeAll()
        myUserInfo.removeAll()
        myUserInfo = LDUserInfo.sharedInstance.userInfoDict
        myExpectJobArr = myUserInfo["expectedjobs"] as! Array<AnyObject>
        tableView?.reloadData()
    }
    
    override func viewDidAppear(animated: Bool) {
        setupData()
    }
    
    func sendRequest() {
        //查询求职状态
        LDCheckPublicInfo.shareInstance.checkoutMyStatus { (data) in
            self.selectTitleArr = data
        }
    }
    
    //增加删除 增加 选中 通知
    func sendNofiEditJob(type:String) {
        
        NSNotificationCenter.defaultCenter().postNotificationName(NotiEidtExpJobName, object: self, userInfo: ["type":type])
    }
    
    func setDefaultContent() {
        title = "管理期望工作"
        view.backgroundColor = LDGolbalColor.BgGoundGray
        tableView = LDBaseTableView.init(frame: view.bounds, style: UITableViewStyle.Plain)
        tableView?.delegate = self
        tableView?.dataSource = self
        tableView?.translatesAutoresizingMaskIntoConstraints = true
        
        
        addJobTitleBtn = UIButton.setDetailsBtn("＋ 期望职位", picName: nil, btnBackColor: LDGolbalColor.Green, titleColor: LDFontColor.White)
        
        view.addSubview(tableView!)
        view.addSubview(addJobTitleBtn!)
        
        tableView?.snp_makeConstraints(closure: { (make) in
            make.left.top.right.equalTo(0)
            make.bottom.equalTo(view).offset(-45 - 40)
        })
        
        addJobTitleBtn?.snp_makeConstraints(closure: { (make) in
            make.left.equalTo(LDMargin_H*2)
            make.right.equalTo(-LDMargin_H*2)
            make.height.equalTo(45)
            make.bottom.equalTo(-LDMargin_H*4)
        })
        //增加期望jobs
        addJobTitleBtn?.bk_whenTapped({[weak self] in
            self?.creatEditManagerJob(.Add,index: nil)
            })
    }
    
    deinit {
        
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
}
extension manageMyResumeVC:UITableViewDelegate,UITableViewDataSource {
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return (myExpectJobArr.count) + 1
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        if indexPath.row == 0 {
            
            var cell = tableView.dequeueReusableCellWithIdentifier("cellshead") as? baseMySettingCells
            if cell == nil {
                cell = baseMySettingCells.init(style: UITableViewCellStyle.Default, reuseIdentifier: "cellshead")
            }
            cell!.titleLab?.textColor = LDFontColor.DeepGray
            cell!.titleLab?.text = "求职状态"
            cell?.selectionStyle = .None
            cell!.descLab?.text = LDUserInfo.sharedInstance.myRemuseInfoDict["status"] as? String
            return cell!
            
        } else {
            
            let dict = myExpectJobArr[indexPath.row - 1] as! NSDictionary
            
            var cell = tableView.dequeueReusableCellWithIdentifier("cellscenter") as? manageMyResumeCells
            if cell == nil {
                cell = manageMyResumeCells.init(style: .Default, reuseIdentifier: "cellscenter")
            }
            
            cell?.tapBtnSelColsure({ (selcell) in
                
                if selcell.isCurrentExpJob == false {
                    
                    let jobid:String = selcell.expectjobid ?? ""
                    
                    LDUserInfoNet.sharedInstance.setMyResumeExpCurrentJob(jobid,
                        success: { [weak self] (value) in
                            
                            LDUserInfo.sharedInstance.updateUserInfo({ (dict) in
                                
                                NSOperationQueue.mainQueue().addOperationWithBlock {
                                    
                                    self?.setupData()
                                    self?.sendNofiEditJob("修改默认职位job_id:\(jobid)")
                                    
                                }
                                
                                LDShowHUB.shareInstance.showSucc("切换成功")
                                }, failure: nil)
                            
                            
                            
                            
                        }, failure: { (data) in
                            LDShowHUB.shareInstance.showSucc("切换失败")
                    })
                }
            })
            print("xx")
            cell?.selexp_id = myUserInfo["expectjobid"] as? String ?? ""
            cell?.model = LDUserInfoExpectedJobModel.yy_modelWithDictionary(dict as [NSObject : AnyObject])
            return cell!
        }
    }
    
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        if indexPath.row == 0 {
            return 50
        } else {
            return 80
        }
    }
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        if indexPath.row == 0 {
            creatAction()
        } else {
            creatEditManagerJob(.Edit,index: indexPath)
        }
    }
    
    func choseStatus(title:String,id:String) {
        
        debugPrint(title,"index")
        LDUserInfoNet.sharedInstance.updateJobStatus(id, success: { [weak self] in
            
            LDUserInfo.sharedInstance.updataJobFinderMyResume({ (dict) in
                
                self?.tableView?.reloadData()
                }, failure: nil)
            
            LDShowHUB.shareInstance.showSucc("状态更改成功")
        }) {
            
            LDShowHUB.shareInstance.showErr("状态更改失败")
        }
    }
    
    func creatEditManagerJob(type:expectJobType,index:NSIndexPath?) {
        
        let vc = manageMyResumeEditJob()
        vc.type = type
        if index != nil {
            vc.params = myExpectJobArr[index!.row - 1] as? Dictionary<NSObject, AnyObject>
        }
        
        navigationController?.pushViewController(vc, animated: true)
    }
    
    func creatAction() {
        
        let labsTitleArr:[String] = {
            
            var arrTitle = [String]()
            for item in selectTitleArr {
                
                let title = item["status_text"] as! String
                arrTitle.append(title)
            }
            
            return arrTitle
        }()
        
        showLDActionSheetView("",labHeight: 0, labsTitleArr: labsTitleArr, selClosure: { (index) in
            
            let choseTitle:String = labsTitleArr[index]
            self.choseStatus(choseTitle, id: String(index + 1))
            
        }) {
            
        }
    }
}